package net.appsec.webapp.controller;

import java.awt.Image;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.appsec.webapp.util.web.check.Validata;
import net.appsec.webapp.util.web.check.paint.ImageFace;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping({ "/resource" })
public class ResourceController {

	@Autowired
	private Validata validata;

	@Autowired
	private ImageFace imageFace;

	@RequestMapping({ "/code" })
	public ModelAndView generateValidationImage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setDateHeader("Expires", 0L);

		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");

		response.addHeader("Cache-Control", "post-check=0, pre-check=0");

		response.setHeader("Pragma", "no-cache");

		response.setContentType("image/jpeg");

		Image bi = this.imageFace.createImage(this.validata);

		request.getSession().setAttribute("session_validation_code",
				this.validata.getLastCheck());
		ServletOutputStream out = response.getOutputStream();

		this.imageFace.store(bi, out);
		try {
			out.flush();
		} finally {
			out.close();
		}
		return null;
	}
}